package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setmealMapper;
    @Override
    public boolean save(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Category category1 = categoryMapper.findByName(category.getName());
        if (category1!=null){
            throw new BusinessException("分类名称已存在");
        }
       return categoryMapper.save(category)>0;
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Category> categoryList = categoryMapper.findAll();
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> pageObj = new Page<Category>();
        pageObj.setRecords(pageInfo.getList());
        pageObj.setTotal(pageInfo.getTotal());
        return pageObj;
    }

    @Override
    public Boolean delete(Long id) {
        Integer count = dishMapper.countByDish(id);
        if (count>0){
            throw new BusinessException("该类别有菜品无法删除");
        }
        Integer count1 = setmealMapper.countBySetmeal(id);
        if (count1>0){
            throw new BusinessException("该类别下有套餐无法删除");
        }
       return categoryMapper.delete(id)>0;
    }

    @Override
    public Boolean update(Category category) {
        Category category1 = categoryMapper.findByName2(category);
        if (category1!=null){
            throw new BusinessException("分类名称已存在,修改失败");
        }
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.update(category)>0;
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public List<Category> findByType(Integer type) {
        return categoryMapper.findByType(type);
    }
}
